In [7]:
# This tutorial demonstrates how to successively add curves and/or data to
# a single plot.

# I will first import the module numpy and 'matplotlib' which we will use
# for ploting.  Matplotlib provides a MATLAB-like interface.  Many of the 
# options used for plotting in MATLAB are the same in Matplotlib.
import math
import numpy as np
import matplotlib.pyplot as plt
In [8]:
# In basic_plots.py, we said that it was easy to put multiple curves on a
# single plot by specifying multiple functions in a single plot command.

#First, we use arange to create an array of numbers from 0 to 2*pi in 
# steps of 0.1.  We convert to an array so that we can later use xx in calculations.
xx = np.array(np.arange(0, 2*math.pi, 0.1))
xx
Out[8]:
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2,
       1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5,
       2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8,
       3.9, 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5. , 5.1,
       5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6. , 6.1, 6.2])
In [9]:
# Here's a plot with two curves (cos and sin).
plt.plot(xx, np.sin(xx), 'k-', xx, np.cos(xx), 'r:', linewidth = 2)
plt.xlabel('x')
plt.ylabel('y')
plt.axis((0, 2*math.pi, -1, 1));
In [10]:
# What if we now wanted to add a third curve to our plot?  We just write another
# plt.plot statement and it will be added to the graph that we already started.

# First, reproduce the original plot.
plt.plot(xx, np.sin(xx), 'k-', xx, np.cos(xx), 'r:', linewidth = 2)
plt.xlabel('x')
plt.ylabel('y')
plt.axis((0, 2*math.pi, -1, 1))

# Now add the new curve.
plt.plot(xx, np.sin(xx)**2, 'b--', linewidth = 2);
In [11]:
# We can continue to add to our existing plot.  Let's also add a legend to 
# the plot.

# First, reproduce the original plot.
plt.plot(xx, np.sin(xx), 'k-', xx, np.cos(xx), 'r:', linewidth = 2)
plt.xlabel('x')
plt.ylabel('y')
plt.axis((0, 2*math.pi, -1, 1))

# Now add the new curve.
plt.plot(xx, np.sin(xx)**2, 'b--', linewidth = 2)

# Add another new curve and the legend.
plt.plot(xx, np.cos(xx)**2, 'g-.', linewidth = 2)
plt.legend((r'$\sin x$', r'$\cos x$', r'$\sin^2 x$', r'$\cos^2 x$'),\
           loc = 'lower left', frameon=False);
In [12]:
# Using a for loop, we can easily add many curve to a single
# plot.  In the loop below, normrnd(mu, sigma) is used to generate random
# numbers drawn from a normal distribution with mean mu and standard
# deviation sigma.  The normally-distributed random number is obtained using
# 'np.random.normal(mu, sigma)' and 'for i in range(10)' loops i from 0 to 9. 
xx = np.array(np.arange(0, 100, 1))
plt.plot(xx, xx**2, 'k-')
plt.xlabel('x')
plt.ylabel('y')
plotformat = ['k--', 'k:', 'k-.', 'r-', 'r--', 'r:', 'r-.', 'b-', 'b--', 'b:'];
mu = 2
sigma = 0.05
for i in range(10):
    n = np.random.normal(mu, sigma)
    plt.plot(xx, xx**n, plotformat[i]);